package com.gin.kotlin.no_gay_alliance.argument

import android.os.Parcelable
import com.gin.nga.enums.param.PostAction
import kotlinx.parcelize.Parcelize
import okhttp3.HttpUrl.Companion.toHttpUrl

/**
 * 发帖准备参数
 * @property action Action
 * @property forumId 版面ID,  action = NEW 时与 colTid 二选一
 * @property colTid 合集ID，  action = NEW 时与 forumId 二选一
 * @property topicId 主题ID， action != NEW 时必须
 * @property replyId 回复目标ID，action != NEW 时可选，留空或填0表示回复主楼
 * @property isComment 是否使用评论贴条形式回复
 * @constructor
 */
@Parcelize
data class PostPrepareArgument(
    val action: Action,
    val forumId: Long? = null,
    val colTid: Long? = null,
    val topicId: Long? = null,
    val replyId: Long? = null,
    val isComment: Boolean = false,
) : Parcelable {

    companion object {
        /**
         * 从url中解析参数
         * @param url String?
         * @return ReplyListArgument?
         */
        fun parseUrl(url: String?): PostPrepareArgument? {
            val httpUrl = url?.toHttpUrl() ?: return null

            val action = httpUrl.queryParameter("action").let { Action.findByName(it) } ?: return null
            val forumId = httpUrl.queryParameter("fid")?.toLong()
            val topicId = httpUrl.queryParameter("tid")?.toLong()
            val colTid = httpUrl.queryParameter("stid")?.toLong()
            val replyId = httpUrl.queryParameter("pid")?.toLong()
            val isComment = httpUrl.queryParameter("comment") != null
            return PostPrepareArgument(action, forumId, colTid, topicId, replyId, isComment)
        }
    }

    /**
     * 操作类型
     */
    @Parcelize
    enum class Action : Parcelable {
        /**
         * 新主题
         */
        NEW,

        /**
         * 回复或评论(贴条)
         */
        REPLY,

        /**
         * 引用
         */
        QUOTE,

        /**
         * 编辑
         */
        MODIFY,

        ;

        fun toPostAction() = PostAction.entries.first { it.name .equals(this.name,true) }

        companion object {
            fun findByName(name: String?) = Action.entries.firstOrNull { it.name.equals(name, true) }
        }
    }
}